/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tcc.ejb.controleProjeto.controle;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import tcc.ejb.controleProjeto.controle.exceptions.IllegalOrphanException;
import tcc.ejb.controleProjeto.controle.exceptions.NonexistentEntityException;
import tcc.ejb.controleProjeto.controle.exceptions.PreexistingEntityException;
import tcc.ejb.controleProjeto.entidade.Diario;
import tcc.ejb.controleProjeto.entidade.Release;
import tcc.ejb.controleProjeto.entidade.Evento;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Maciel
 */
public class DiarioJpaController {

    public DiarioJpaController() {
        emf = Persistence.createEntityManagerFactory("WebApplication4PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Diario diario) throws PreexistingEntityException, Exception {
        if (diario.getEventoList() == null) {
            diario.setEventoList(new ArrayList<Evento>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Release release = diario.getRelease();
            if (release != null) {
                release = em.getReference(release.getClass(), release.getId());
                diario.setRelease(release);
            }
            List<Evento> attachedEventoList = new ArrayList<Evento>();
            for (Evento eventoListEventoToAttach : diario.getEventoList()) {
                eventoListEventoToAttach = em.getReference(eventoListEventoToAttach.getClass(), eventoListEventoToAttach.getId());
                attachedEventoList.add(eventoListEventoToAttach);
            }
            diario.setEventoList(attachedEventoList);
            em.persist(diario);
            if (release != null) {
                release.getDiarioList().add(diario);
                release = em.merge(release);
            }
            for (Evento eventoListEvento : diario.getEventoList()) {
                Diario oldDiarioOfEventoListEvento = eventoListEvento.getDiario();
                eventoListEvento.setDiario(diario);
                eventoListEvento = em.merge(eventoListEvento);
                if (oldDiarioOfEventoListEvento != null) {
                    oldDiarioOfEventoListEvento.getEventoList().remove(eventoListEvento);
                    oldDiarioOfEventoListEvento = em.merge(oldDiarioOfEventoListEvento);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findDiario(diario.getId()) != null) {
                throw new PreexistingEntityException("Diario " + diario + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Diario diario) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Diario persistentDiario = em.find(Diario.class, diario.getId());
            Release releaseOld = persistentDiario.getRelease();
            Release releaseNew = diario.getRelease();
            List<Evento> eventoListOld = persistentDiario.getEventoList();
            List<Evento> eventoListNew = diario.getEventoList();
            List<String> illegalOrphanMessages = null;
            for (Evento eventoListOldEvento : eventoListOld) {
                if (!eventoListNew.contains(eventoListOldEvento)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Evento " + eventoListOldEvento + " since its diario field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (releaseNew != null) {
                releaseNew = em.getReference(releaseNew.getClass(), releaseNew.getId());
                diario.setRelease(releaseNew);
            }
            List<Evento> attachedEventoListNew = new ArrayList<Evento>();
            for (Evento eventoListNewEventoToAttach : eventoListNew) {
                eventoListNewEventoToAttach = em.getReference(eventoListNewEventoToAttach.getClass(), eventoListNewEventoToAttach.getId());
                attachedEventoListNew.add(eventoListNewEventoToAttach);
            }
            eventoListNew = attachedEventoListNew;
            diario.setEventoList(eventoListNew);
            diario = em.merge(diario);
            if (releaseOld != null && !releaseOld.equals(releaseNew)) {
                releaseOld.getDiarioList().remove(diario);
                releaseOld = em.merge(releaseOld);
            }
            if (releaseNew != null && !releaseNew.equals(releaseOld)) {
                releaseNew.getDiarioList().add(diario);
                releaseNew = em.merge(releaseNew);
            }
            for (Evento eventoListNewEvento : eventoListNew) {
                if (!eventoListOld.contains(eventoListNewEvento)) {
                    Diario oldDiarioOfEventoListNewEvento = eventoListNewEvento.getDiario();
                    eventoListNewEvento.setDiario(diario);
                    eventoListNewEvento = em.merge(eventoListNewEvento);
                    if (oldDiarioOfEventoListNewEvento != null && !oldDiarioOfEventoListNewEvento.equals(diario)) {
                        oldDiarioOfEventoListNewEvento.getEventoList().remove(eventoListNewEvento);
                        oldDiarioOfEventoListNewEvento = em.merge(oldDiarioOfEventoListNewEvento);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = diario.getId();
                if (findDiario(id) == null) {
                    throw new NonexistentEntityException("The diario with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Diario diario;
            try {
                diario = em.getReference(Diario.class, id);
                diario.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The diario with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Evento> eventoListOrphanCheck = diario.getEventoList();
            for (Evento eventoListOrphanCheckEvento : eventoListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Diario (" + diario + ") cannot be destroyed since the Evento " + eventoListOrphanCheckEvento + " in its eventoList field has a non-nullable diario field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Release release = diario.getRelease();
            if (release != null) {
                release.getDiarioList().remove(diario);
                release = em.merge(release);
            }
            em.remove(diario);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Diario> findDiarioEntities() {
        return findDiarioEntities(true, -1, -1);
    }

    public List<Diario> findDiarioEntities(int maxResults, int firstResult) {
        return findDiarioEntities(false, maxResults, firstResult);
    }

    private List<Diario> findDiarioEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Diario.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Diario findDiario(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Diario.class, id);
        } finally {
            em.close();
        }
    }

    public int getDiarioCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Diario> rt = cq.from(Diario.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
